package ua.com.fesvlast.hotel.controller;


import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ua.com.fesvlast.hotel.controller.managers.ConfigurationManager;
import ua.com.fesvlast.hotel.controller.managers.ConnectionManagerTOMCAT;
import ua.com.fesvlast.hotel.controller.managers.MessageManager;
import ua.com.fesvlast.hotel.model.commands.ICommand;



@WebServlet("/Controller")
public class Controller extends HttpServlet {
	private static final long serialVersionUID = 1L;
     RequestHelper requestHelper=RequestHelper.getInstance();  
     
    
    public Controller() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			String page =null;
			
			try{
				ICommand command=requestHelper.getCommand(request);
				
				page=command.execute(request, response);
				
				
			}catch(ServletException e){
				e.printStackTrace();
				
				request.setAttribute("errorMessage", MessageManager.getInstance().getProperty(
						MessageManager.SERVLET_EXCEPTION_ERROR_MESSAGE));
				
				page=ConfigurationManager.getInstance().getProperty(ConfigurationManager.ERROR_PAGE_PATH);
			}catch(IOException e){
				e.printStackTrace();
				request.setAttribute("errorMessage", MessageManager.getInstance().getProperty(
						MessageManager.IO_EXCEPTION_ERROR_MESSAGE));
				
				page=ConfigurationManager.getInstance().getProperty(ConfigurationManager.ERROR_PAGE_PATH);
			}
			
			RequestDispatcher dispatcher=getServletContext().getRequestDispatcher(page);
			dispatcher.forward(request, response);
		
	}

}
